package com.hziee.cosmanage.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.support.BiIntFunction;
import com.hziee.cosmanage.search.config.ESConfig;
import com.hziee.cosmanage.search.constant.COSConstant;
import com.hziee.cosmanage.search.service.ElasticInviteService;
import com.hziee.cosmanage.search.vo.InviteVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ElasticInviteServiceImpl implements ElasticInviteService {

    @Resource
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean inviteStatusUp(List<InviteVo> vos) throws IOException {
        //保存到es
        //保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (InviteVo vo : vos) {
            //1.构造保存请求
            IndexRequest indexRequest = new IndexRequest(COSConstant.INVITE_INDEX);
            indexRequest.id(vo.getCompanyInviteId().toString());
            String string = JSON.toJSONString(vo);
            indexRequest.source(string, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ESConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.error("招聘信息上传成功：{}"+collect);
        return b;
    }

    @Override
    public boolean updateESInvite(InviteVo vo) throws IOException {
        UpdateRequest request = new UpdateRequest(COSConstant.INVITE_INDEX, vo.getEsId().toString());
        request.timeout("1s");
        vo.setStatus(0);
        vo.setEsId(null);
        UpdateRequest doc = request.doc(JSON.toJSONString(vo), XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(doc, ESConfig.COMMON_OPTIONS);
        if ("OK".equals(update)) {
            return true;
        }else {
            return false;
        }
    }
}
